<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="用户昵称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="注册时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['cms:user:add']"-->
<!--        >新增-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['cms:user:edit']"-->
<!--        >修改-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['cms:user:remove']"-->
<!--        >删除-->
<!--        </el-button>-->
<!--      </el-col>-->

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList"  >
      <el-table-column label="用户uid" align="center" prop="uid"/>
      <el-table-column label="用户昵称" align="center" prop="name"/>
      <el-table-column label="用户邮箱" align="center" prop="email"/>
<!--      <el-table-column label="用户手机号" align="center" prop="phone"/>-->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 1">正常</span>
          <span v-else-if="scope.row.status === -1">删除</span>
          <span v-else>{{ scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户头像" align="center" prop="portrait">
        <template slot-scope="scope">
          <img v-if="scope.row.portrait" :src="scope.row.portrait" alt="用户头像" style="width: 50px; height: 50px; border-radius: 50%;">
          <i v-else class="el-icon-user-solid" style="font-size: 30px; color: #ccc;"></i>
        </template>
      </el-table-column>
<!--      <el-table-column label="用户介绍" align="center" prop="intro"/>-->
      <el-table-column label="注册时间" align="center" prop="t">
        <template slot-scope="scope">
          {{ formatDate(scope.row.t) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情
          </el-button>
          <el-button
             v-if="scope.row.status === 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['cms:user:remove']"
          >删除
          </el-button>
          <el-button
            v-if="scope.row.status === 1"
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleResetPassword(scope.row)"
          >重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 重置密码对话框 -->
    <el-dialog :title="title" :visible.sync="openResetPassword" width="500px" append-to-body>
      <el-form ref="resetPasswordForm" :model="resetPasswordForm" :rules="resetPasswordRules" label-width="80px">
        <el-form-item label="用户ID" prop="uid">
          <el-input v-model="resetPasswordForm.uid" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="resetPasswordForm.password" placeholder="请输入新密码" show-password />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitResetPassword">确 定</el-button>
        <el-button @click="cancelResetPassword">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getUserDetail, listUser,delUser,resetPassword} from "@/api/user/user"

export default {
  name: "User",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户管理表格数据
      userList: [],
      // 时间范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 重置密码弹出层
      openResetPassword: false,
      // 重置密码表单
      resetPasswordForm: {
        uid: undefined,
        password: undefined
      },
      // 重置密码表单校验
      resetPasswordRules: {
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: "密码长度应在6到20位之间", trigger: "blur" }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        phone: null,
        status: null,
        email: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询用户管理列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 格式化时间戳为日期时间格式
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(parseInt(timestamp));
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        uid: null,
        name: null,
        phone: null,
        label: null,
        status: null,
        email: null,
        portrait: null,
        intro: null,
        t: null,
        md5: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.params = {};
      if (this.dateRange && this.dateRange.length > 0) {
        this.queryParams.params.startTime = this.dateRange[0];
        this.queryParams.params.endTime = this.dateRange[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.uid)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("/user/add");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push("/user/edit/" + row.uid);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateLink(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addLink(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.uid + '"的数据项？').then(function () {
        return delUser(row.uid)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 重置密码按钮操作 */
    handleResetPassword(row) {
      this.resetPasswordForm.uid = row.uid;
      this.openResetPassword = true;
    },
    /** 提交重置密码 */
    submitResetPassword() {
      this.$refs["resetPasswordForm"].validate(valid => {
        if (valid) {
          resetPassword(this.resetPasswordForm.uid, this.resetPasswordForm.password).then(response => {
            this.$modal.msgSuccess("重置密码成功");
            this.openResetPassword = false;
            this.getList();
          });
        }
      });
    },
    /** 取消重置密码 */
    cancelResetPassword() {
      this.openResetPassword = false;
      this.resetPasswordForm = {
        uid: undefined,
        password: undefined
      };
    },
    /** 详情按钮操作 */
    handleView(row) {
      this.$router.push({
        path: '/user/detail/' + row.uid,
        query: { uid: row.uid }
      });
    }
  }
}
</script>
